<template>
  <div class="container">
    <div class="filter-container">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="医生姓名">
          <el-input v-model="searchForm.doctorName" placeholder="请输入医生姓名" />
        </el-form-item>
        <el-form-item label="科室">
          <el-cascader
            v-model="searchForm.deptId"
            :options="departmentOptions"
            :props="{ 
              checkStrictly: true,
              value: 'id',
              label: 'departmentName',
              children: 'children'
            }"
            placeholder="请选择科室"
            clearable
          />
        </el-form-item>
        <el-form-item label="职称">
          <el-select v-model="searchForm.jobTitleId" placeholder="请选择职称" style="width: 100%">
            <el-option v-for="item in titleOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="服务状态">
          <el-select v-model="searchForm.serviceStatus" placeholder="请选择服务状态">
            <el-option label="全部" value="" />
            <el-option label="待审核" value="待审核" />
            <el-option label="已通过" value="已通过" />
            <el-option label="未通过" value="未通过" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">筛选</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <el-tab-pane label="全部" name="all"></el-tab-pane>
      <el-tab-pane label="待审核" name="pending"></el-tab-pane>
      <el-tab-pane label="已通过" name="approved"></el-tab-pane>
      <el-tab-pane label="未通过" name="rejected"></el-tab-pane>
    </el-tabs>

    <div class="table-container">
      <div class="table-header">
        <el-button type="danger" :disabled="selectedServices.length === 0" @click="handleBatchDelete">批量删除</el-button>
      </div>
      
      <el-table 
        :data="serviceList" 
        border 
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="doctorName" label="医生姓名" width="120" />
        <el-table-column prop="serviceName" label="服务名称" width="150" />
        <el-table-column prop="serviceType" label="服务类型" width="120" />
        <el-table-column prop="price" label="价格(元)" width="100">
          <template #default="scope">
            {{ scope.row.price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="hospitalName" label="医院" />
        <el-table-column prop="departmentName" label="科室" width="120" />
        <el-table-column prop="serviceStatus" label="服务状态" width="120">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.serviceStatus)">{{ getStatusText(scope.row.serviceStatus) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" align="center">
          <template #default="scope">
            <el-button size="small" @click="viewService(scope.row)">查看</el-button>
            <el-button v-if="scope.row.serviceStatus !== '已通过'" size="small" type="success" @click="approveService(scope.row)">通过</el-button>
            <el-button v-if="scope.row.serviceStatus !== '未通过'" size="small" type="danger" @click="rejectService(scope.row)">拒绝</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          :page-size="searchForm.pageSize"
          :current-page="searchForm.pageIndex"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 审核详情对话框 -->
    <el-dialog v-model="auditDialogVisible" title="服务审核" width="70%">
      <div class="audit-content">
        <div class="service-info">
          <h3>服务信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="服务名称">{{ currentService.serviceName }}</el-descriptions-item>
            <el-descriptions-item label="服务类型">{{ currentService.serviceType }}</el-descriptions-item>
            <el-descriptions-item label="价格">{{ currentService.price ? `¥${currentService.price.toFixed(2)}` : '-' }}</el-descriptions-item>
            <el-descriptions-item label="服务时长">{{ currentService.duration }}分钟</el-descriptions-item>
            <el-descriptions-item label="医生姓名">{{ currentService.doctorName }}</el-descriptions-item>
            <el-descriptions-item label="科室">{{ currentService.departmentName }}</el-descriptions-item>
            <el-descriptions-item label="医院">{{ currentService.hospitalName }}</el-descriptions-item>
          </el-descriptions>
        </div>
        
        <div class="service-description">
          <h3>服务描述</h3>
          <div class="description-content">
            <p>{{ currentService.description || '暂无服务描述' }}</p>
          </div>
        </div>

        <div class="audit-form">
          <el-form :model="auditForm">
            <el-form-item label="审核意见">
              <el-input v-model="auditForm.comment" type="textarea" :rows="4" placeholder="请输入审核意见"></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="auditDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmReject">拒绝</el-button>
          <el-button type="primary" @click="confirmApprove">通过</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getDepartmentsCascade } from '@/http/axiosRead'
import { deleteDoctor, batchDeleteDoctors } from '@/http/axiosWrtie'

// 定义服务接口
interface Service {
  id: number;
  doctorName: string;
  serviceName: string;
  serviceType: string;
  price: number;
  duration: number;
  hospitalName: string;
  departmentName: string;
  serviceStatus: string;
  description: string;
  [key: string]: any;
}

// 示例数据，实际项目中应该从API获取
const departmentOptions = ref([])

const titleOptions = ref([
  { id: 1, name: '主任医师' },
  { id: 2, name: '副主任医师' },
  { id: 3, name: '主治医师' },
  { id: 4, name: '住院医师' },
  { id: 5, name: '药剂师' },
  { id: 6, name: '护士' }
])

const searchForm = reactive({
  doctorName: '',
  deptId: undefined,
  jobTitleId: undefined,
  serviceStatus: '',
  pageIndex: 1,
  pageSize: 10
})

const serviceList = ref<Service[]>([
  {
    id: 1,
    doctorName: '秦山',
    serviceName: '图文问诊',
    serviceType: '线上问诊',
    price: 100,
    duration: 30,
    hospitalName: '北大医院',
    departmentName: '内科',
    serviceStatus: '待审核',
    description: '为患者提供专业的图文问诊服务，解答患者疑问，提供专业建议。'
  },
  {
    id: 2,
    doctorName: '张三',
    serviceName: '视频问诊',
    serviceType: '线上问诊',
    price: 200,
    duration: 15,
    hospitalName: '北大医院',
    departmentName: '内科',
    serviceStatus: '已通过',
    description: '为患者提供一对一的视频问诊服务，可视化交流，更加直观。'
  },
  {
    id: 3,
    doctorName: '秦山',
    serviceName: '线下门诊',
    serviceType: '线下服务',
    price: 300,
    duration: 20,
    hospitalName: '北大医院',
    departmentName: '内科',
    serviceStatus: '未通过',
    description: '提供线下面对面诊疗服务，全面检查，详细诊断。'
  }
])

const selectedServices = ref<Service[]>([])
const total = ref(30)
const activeTab = ref('all')
const auditDialogVisible = ref(false)
const currentService = ref({
  id: 0,
  doctorName: '',
  serviceName: '',
  serviceType: '',
  price: 0,
  duration: 0,
  hospitalName: '',
  departmentName: '',
  serviceStatus: '',
  description: ''
})

const auditForm = reactive({
  comment: ''
})

onMounted(() => {
  fetchDepartmentList()
  fetchServiceList()
})

const handleSelectionChange = (selection: Service[]) => {
  selectedServices.value = selection
}

const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确认删除服务 ${row.serviceName}？`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await deleteDoctor(row.id)
      if (response.data && response.data.code === 200) {
        ElMessage.success('删除成功')
        fetchServiceList()
      } else {
        ElMessage.error(response.data?.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除服务失败：', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }).catch(() => {
    // 取消删除，不做处理
  })
}

const handleBatchDelete = () => {
  if (selectedServices.value.length === 0) {
    return
  }
  
  ElMessageBox.confirm(`确认删除选中的 ${selectedServices.value.length} 个服务？`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const ids = selectedServices.value.map(service => service.id)
      const response = await batchDeleteDoctors(ids)
      if (response.data && response.data.code === 200) {
        ElMessage.success('批量删除成功')
        fetchServiceList()
      } else {
        ElMessage.error(response.data?.msg || '批量删除失败')
      }
    } catch (error) {
      console.error('批量删除服务失败：', error)
      ElMessage.error('批量删除失败，请稍后重试')
    }
  }).catch(() => {
    // 取消删除，不做处理
  })
}

const fetchDepartmentList = async () => {
  try {
    const response = await getDepartmentsCascade()
    if (response.data && response.data.data && response.data.data.departments) {
      departmentOptions.value = response.data.data.departments
    }
  } catch (error) {
    console.error('获取科室列表失败：', error)
    ElMessage.error('获取科室列表失败')
  }
}

const fetchServiceList = () => {
  // 这里应该调用API获取服务列表
  // 模拟根据标签页筛选数据
  switch(activeTab.value) {
    case 'pending':
      serviceList.value = serviceList.value.filter(item => item.serviceStatus === '待审核')
      break
    case 'approved':
      serviceList.value = serviceList.value.filter(item => item.serviceStatus === '已通过')
      break
    case 'rejected':
      serviceList.value = serviceList.value.filter(item => item.serviceStatus === '未通过')
      break
    default:
      // 'all' 标签，不做过滤
      break
  }
}

const handleTabClick = () => {
  searchForm.pageIndex = 1
  fetchServiceList()
}

const onSearch = () => {
  searchForm.pageIndex = 1
  fetchServiceList()
}

const resetForm = () => {
  searchForm.doctorName = ''
  searchForm.deptId = undefined
  searchForm.jobTitleId = undefined
  searchForm.serviceStatus = ''
  activeTab.value = 'all'
  onSearch()
}

const handleSizeChange = (val: number) => {
  searchForm.pageSize = val
  fetchServiceList()
}

const handleCurrentChange = (val: number) => {
  searchForm.pageIndex = val
  fetchServiceList()
}

const getStatusType = (status: string) => {
  switch (status) {
    case '已通过':
      return 'success'
    case '未通过':
      return 'danger'
    case '待审核':
    default:
      return 'info'
  }
}

const getStatusText = (status: string) => {
  return status || '待审核'
}

const viewService = (row: any) => {
  currentService.value = { ...row }
  auditDialogVisible.value = true
  auditForm.comment = ''
}

const approveService = (row: any) => {
  currentService.value = { ...row }
  auditDialogVisible.value = true
  auditForm.comment = '服务审核通过'
}

const rejectService = (row: any) => {
  currentService.value = { ...row }
  auditDialogVisible.value = true
  auditForm.comment = '服务审核未通过，请修改后重新提交'
}

const confirmApprove = () => {
  ElMessage.success(`服务审核通过：${currentService.value.serviceName}`)
  auditDialogVisible.value = false
  // 这里应该调用API进行服务状态更新
  // 模拟更新状态
  const index = serviceList.value.findIndex(item => item.id === currentService.value.id)
  if (index !== -1) {
    serviceList.value[index].serviceStatus = '已通过'
  }
}

const confirmReject = () => {
  ElMessage.warning(`服务审核拒绝：${currentService.value.serviceName}`)
  auditDialogVisible.value = false
  // 这里应该调用API进行服务状态更新
  // 模拟更新状态
  const index = serviceList.value.findIndex(item => item.id === currentService.value.id)
  if (index !== -1) {
    serviceList.value[index].serviceStatus = '未通过'
  }
}
</script>

<style scoped>
.container {
  padding: 20px;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.filter-container {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f8f8f8;
  border-radius: 8px;
}

.table-container {
  margin-top: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.audit-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.service-info, .service-description, .audit-form {
  margin-bottom: 20px;
}

.description-content {
  padding: 15px;
  background-color: #f8f8f8;
  border-radius: 4px;
  min-height: 100px;
}

.table-header {
  margin-bottom: 15px;
  display: flex;
  justify-content: flex-start;
}
</style> 